package com.framework.websocket.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 测试控制器 - 用于模拟业务数据变化
 */
@RestController
@RequestMapping("/test")
public class TestController {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    /**
     * 更新设备状态
     */
    @PostMapping("/device/{deviceId}/status")
    public Map<String, Object> updateDeviceStatus(
            @PathVariable String deviceId,
            @RequestParam boolean online,
            @RequestParam(required = false) Double temperature) {
        
        Map<String, Object> status = new HashMap<>();
        status.put("deviceId", deviceId);
        status.put("online", online);
        status.put("temperature", temperature != null ? temperature : 0);
        status.put("updateTime", LocalDateTime.now().toString());
        
        // 更新到 Redis，触发键空间通知
        String key = "device:status:" + deviceId;
        redisTemplate.opsForValue().set(key, status);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", status);
        return result;
    }
    
    /**
     * 发送报警
     */
    @PostMapping("/alarm/send")
    public Map<String, Object> sendAlarm(
            @RequestParam String deviceId,
            @RequestParam String alarmType,
            @RequestParam String message) {
        
        Map<String, Object> alarm = new HashMap<>();
        alarm.put("alarmId", System.currentTimeMillis());
        alarm.put("deviceId", deviceId);
        alarm.put("alarmType", alarmType);
        alarm.put("message", message);
        alarm.put("timestamp", LocalDateTime.now().toString());
        
        // 发送到 Redis
        String key = "alarm:notification:" + alarm.get("alarmId");
        redisTemplate.opsForValue().set(key, alarm);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", alarm);
        return result;
    }
    
    /**
     * 获取设备状态
     */
    @GetMapping("/device/{deviceId}/status")
    public Map<String, Object> getDeviceStatus(@PathVariable String deviceId) {
        String key = "device:status:" + deviceId;
        Object status = redisTemplate.opsForValue().get(key);
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", status != null ? status : "未找到设备状态");
        return result;
    }
}